package com.summerli.service;

import com.summerli.common.ResponseResult;
import com.summerli.common.constant.CommonStatusEnum;
import com.summerli.common.seriviceverificationcode.VerifyCodeResponse;
import com.summerli.common.util.RedisKeyUtil;
import com.summerli.service.VerifyCodeService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class VerifyCodeServiceImpl implements VerifyCodeService {

    @Autowired
    StringRedisTemplate redisTemplate;

    //存储redis
    @Override
    public ResponseResult<VerifyCodeResponse> generate(int identity, String phoneNumber) {
        // 三挡校验
        checkSendCodeTimeLimit(phoneNumber);

        // 生成校验码
        String data = String.valueOf((int)((Math.random()*9+1)*Math.pow(10,5)));
        // 存储redis
        String redisPreKey = RedisKeyUtil.generateKeyPreByIdentity(identity);
        String redisKey = redisPreKey + phoneNumber;
        BoundValueOperations<String, String> opertion = redisTemplate.boundValueOps(redisKey);
        opertion.set(data,1, TimeUnit.MINUTES);//设置1分钟过期
        VerifyCodeResponse response = new VerifyCodeResponse();
        response.setData(data);
        return ResponseResult.success(response);
    }

    @Override
    public ResponseResult<VerifyCodeResponse> verify(int identity, String phoneNumber, String code) {
        // 三档校验

        String preKey = RedisKeyUtil.generateKeyPreByIdentity(identity);
        BoundValueOperations<String, String> operation = redisTemplate.boundValueOps(preKey + phoneNumber);
        String redisCode = operation.get();
        if(StringUtils.isNotBlank(redisCode)
            && StringUtils.isNotBlank(code) && redisCode.equals(code)){
            return ResponseResult.success("");
        }
        return ResponseResult.fail(CommonStatusEnum.VERIFY_CODE_ERROR.getCode(), CommonStatusEnum.VERIFY_CODE_ERROR.getValue());
    }

    // 判断是否有 限制1分钟，10分钟，24小时，手机号发送验证码的次数限制
    private void checkSendCodeTimeLimit(String phoneNumber) {

    }
}
